import { useState } from 'react'
import { produce } from 'immer'

const Demo2 = () => {
  const [user, setUser] = useState({ username: '晓华', age: 18 })
  const [hobbys, setHobby] = useState([
    { id: 1, title: '吃饭' },
    { id: 2, title: '找工作' },
  ])

  const handle3 = (id) => {
    const index = hobbys.findIndex((item) => item.id === id)
    setHobby(
      produce((hobbys) => {
        hobbys.splice(index, 1)
      })
    )
  }

  const handle2 = () => {
    setHobby(
      produce((hobbys) => {
        hobbys.push({ id: Date.now(), title: '打豆豆' + Math.random() })
      })
    )
  }

  const handle1 = () => {
    setUser(
      produce((user) => {
        user.username = '小安'
      })
    )
  }

  return (
    <>
      <h3>你的爱好</h3>
      <ul>
        {hobbys.map((item) => (
          <li key={item.id}>
            {item.title}
            <span
              onClick={() => {
                handle3(item.id)
              }}
            >
              删除
            </span>
          </li>
        ))}
      </ul>
      <button onClick={handle2}>添加爱好</button>
      <hr />
      <p>{JSON.stringify(user)}</p>
      <button onClick={handle1}>改名</button>
    </>
  )
}

export default Demo2
